package com.idanchuang.support.etcache.pubsub;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 缓存事件队列的默认实现
 * @author yjy
 * Created at 2021/12/23 9:08 下午
 */
public class DefaultSubEventQueue implements SubEventQueue {

    private static final Logger logger = LoggerFactory.getLogger(DefaultSubEventQueue.class);

    /** 队列容器 */
    private final Queue<RemoteEvent> queue = new LinkedBlockingQueue<>();

    @Override
    public void push(RemoteEvent event) {
        synchronized (queue) {
            queue.add(event);
            queue.notifyAll();
        }
        logger.debug("SubEventQueue receive event > {}", event);
    }

    @Override
    public RemoteEvent poll() {
        synchronized (queue) {
            if (queue.isEmpty()) {
                try {
                    queue.wait();
                } catch (Exception e) {
                    logger.warn("poll sub event failed", e);
                }
            }
            RemoteEvent event = queue.poll();
            logger.debug("SubEventQueue poll event > {}", event);
            return event;
        }
    }

}
